<template>
	<view class="content bg_com">
		<!-- 顶部搜索 -->
		<com-nav-bar>
			<template>
				<!-- <uni-nav-bar class="nav_bar" left-icon="back" color="#F1EDFF" backgroundColor="#181526" :left-text="detailMsgSession.other.nick"> -->
				</uni-nav-bar>
				<view class="_nav" @click="navBack">
					<i class="iconfont icon-31fanhui1"></i>
					{{detailMsgSession.other.nick || '顽皮'}}
				</view>
			</template>
		</com-nav-bar>
		<view class="msgBox">
			<view class="MsgCotainer">
				<view class="detail">
					<scroll-view class="msg_scroll" scroll-y="true" :style="{height: scroll_height}"
						:scroll-top="msgScrollTop">
						<view :class="{ 'detail-item': true , 'detail-mine' : item.isMineFlag}"
							v-for="(item,index) in detailMsgSession.msgs" :key="index">
							<!-- <view class="time">07-09 17:12</view> -->
							<div class="detail-content">
								<image class="user-icon" :src='item.isMineFlag ? item.mine.avatar: item.other.avatar '>
								</image>
								<view class="msg">
									{{item.text}}
								</view>
							</div>
						</view>
					</scroll-view>
					<view class="sendBox" :style="{bottom: inputBottom + 'px'}">
						<input type="text" @keyboardheightchange="keyboardheightchange" @blur="blur" placeholder="请输入..." :adjust-position="false" placeholder-style="color:#E5DDFF" v-model="p2pVal"
							@confirm="sendP2PMsg">
						<button class="sendBtn" @click="sendP2PMsg">发送</button>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex';
	import NIM from '../../house/libs/NIM_Web_NIM_miniapp_v8.9.0.js'
	//const appKey = '9bbedb58f17bba7bbf3256f43c8cab91' //云信appKey
	let nimInstance
	export default {
		computed: mapState(['hasLogin', 'user', 'identity', 'tickets']),
		data() {
			return {
				p2pMsgArr: [],
				msgScrollTop: 0,
				detailMsgSession: [],
				p2pVal: '',
				targetUid: '',
				otherInfo: null,
				scroll_height: 0,
				inputBottom: 0
			}
		},
		onLoad(e) {
			console.log(e.targetUid + '这是要聊天的id+++++++++++++++++++++++++++++')
			if (e.targetUid) {
				this.targetUid = e.targetUid;
				this.initNIM();
			}
		},
		onReady() {
			var _this = this;
			uni.getSystemInfo({
				success: (resu) => {
					var pxVal = uni.upx2px(98);
					let tabbarHeight = ((this.menu.top - this.statusBar) * 2 + this.menu.height) + this
						.statusBar;
					console.log(tabbarHeight + "这是高度====================================")
					const query = uni.createSelectorQuery();
					_this.scroll_height = resu.windowHeight - (tabbarHeight + pxVal) + 'px';
				},
				fail: (res) => {}
			})
		},
		methods: {
			navBack() {
				nimInstance.disconnect();
				uni.navigateBack()
			},
			/* 监听键盘高度 */
			keyboardheightchange(e) {
				console.log("==========================>")
				console.log(e)
				this.inputBottom = e.detail.height;
			},
			/* 失去焦点 */
			blur() {
				this.inputBottom = 0;
			},
			//初始化云信账号
			initNIM() {
				const {
					uid,
					netEaseToken
				} = this.identity;
				var _nim = NIM.getInstance({
					debug: false, // 是否开启日志，将其打印到console。集成开发阶段建议打开。
					appKey: this.$urlConfig.appKey,
					account: uid,
					token: netEaseToken,
					db: true, //若不要开启数据库请设置false。SDK默认为true。
					onconnect: () => {
						console.log("+++++++++++++++++++++")
						this.handleIntoMsgDetail();
					},
					onupdatesession: (session) => {
						console.log('updatesession', session)
						this.$set(this.p2pMsgArr, this.p2pMsgArr.findIndex(i => i.to == session.to), {
							...this.p2pMsgArr.find(i => i.to == session.to),
							...session,
						})
						if (session.lastMsg.from != this.identity.uid) {
							if (this.detailMsgSession && this.detailMsgSession.msgs) {
								this.detailMsgSession.msgs.push({
									...session.lastMsg,
									mine: this.user,
									other: this.detailMsgSession.other,
									isMineFlag: false,
								})
								//滚动到底部
							}
							this.msgScrollTop += 80
						}

					},
				});
				nimInstance = _nim;

			},
			timesub(time) {
				var date = new Date(time);
				var year = date.getFullYear();
				var mou = date.getMonth() + 1;
				var day = date.getDate();
				var hours = date.getHours();
				var minutes = date.getMinutes();
				var myDate = new Date();
				var newdate = (myDate.getMonth() * 30) + myDate.getDate();
				var thisdate = (mou * 30) + day;
				hours < 10 ? hours = '0' + hours : null;
				minutes < 10 ? minutes = '0' + minutes : null;
				day < 10 ? day = '0' + day : null;
				mou < 10 ? mou = '0' + mou : null;
				if (myDate.getFullYear() != year) {
					var newtime = year + '-' + mou + '-' + day + ' ' + hours + ':' + minutes;
				} else if (newdate - thisdate > 2) {
					var newtime = mou + '-' + day + ' ' + hours + ':' + minutes;
				} else if (newdate - thisdate == 2) {
					var newtime = '前天 ' + hours + ':' + minutes;
				} else if (newdate - thisdate == 1) {
					var newtime = '昨天 ' + hours + ':' + minutes;
				} else {
					var newtime = hours + ':' + minutes;
				}
				return newtime;
			},

			async handleIntoMsgDetail() { //聊天详情
				await this.$api.userDetail({
					uid: this.identity.uid,
					ticket: this.tickets[0].ticket,
					targetUid: this.targetUid,
				}).then((res) => {
					this.otherInfo = res.data;
				})
				nimInstance.setCurrSession(this.user.uid)
				//滚动到底部
				nimInstance.getHistoryMsgs({
					scene: 'p2p',
					to: this.targetUid,
					reverse: true,
					done: (err, obj) => {
						console.log(err);
						console.log(obj.msgs)
						this.detailMsgSession = {
							...obj,
							mine: this.user,
							other: this.otherInfo,
							msgs: obj.msgs.map(msg => {
								return {
									...msg,
									mine: this.user,
									other: this.otherInfo,
									isMineFlag: msg.from == this.user.uid
								}
							}),
							_item: this.otherInfo
						}
						setTimeout(() => {
							this.msgScrollTop = this.detailMsgSession.msgs.length * 80;
						}, 500);

					}
				});
			},
			open() {
				this.$refs.popupP2pMsgs.open();
			},
			close() {
				this.$refs.popupP2pMsgs.close();
			},
			sendP2PMsg() {
				if(this.p2pVal == '') {
					this.$interactive.toast("请先输入内容");
					return;
				}
				
				nimInstance.sendText({
					scene: 'p2p',
					to: this.targetUid,
					text: this.p2pVal,
					done: (error, msg) => {
						//滚动到底部
						this.p2pVal = ''
						this.detailMsgSession.msgs.push({
							...msg,
							mine: this.user,
							other: this.detailMsgSession.other,
							isMineFlag: true,
						})
						this.msgScrollTop += 80
						console.log(this.msgScrollTop)
					}
				});
			},
			handBackToP2PList() {
				console.log(this.detailMsgSession)
				nimInstance.resetCurrSession()
				this.detailMsgSession = {},
					this.close();
				uni.showTabBar();
			},
		}
	}
</script>

<style lang="scss">
	@import "./index.scss";
</style>
